package com.vy.stl.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vy.stl.entity.Coach;
import com.vy.stl.entity.Course;
import com.vy.stl.mapper.CoachMapper;
import com.vy.stl.mapper.CourseMapper;
import com.vy.stl.service.CoachService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @create: 2025/08/27 17:10
 * @description:
 */
@Service
public class CoachServiceImpl implements CoachService {
    @Autowired
    private CoachMapper coachMapper;

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public List<Coach> search(Coach coach) {
        return coachMapper.select(coach);
    }

    @Override
    public PageInfo searchByPage(Integer pageNum, Integer pageSize, Coach coach) {
        if (ObjectUtils.isEmpty(pageNum)) pageNum = 1;
        if (ObjectUtils.isEmpty(pageSize)) pageSize = 10;
        //开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Coach> coaches = coachMapper.select(coach);
        PageInfo<Coach> pageInfo = new PageInfo<>(coaches);

        return pageInfo;
    }

    @Override
    public Coach getCoachByPhone(String phone) {
        return coachMapper.selectCoachPhone(phone);
    }

    @Override
    public int add(Coach coach) {
        return coachMapper.insert(coach);
    }

    @Override
    public int edit(Coach coach) throws Exception {
        Coach dbCoach = coachMapper.selectCoachPhone(coach.getPhone());
        if (!ObjectUtils.isEmpty(dbCoach) && dbCoach.getId() != coach.getId()) {
            throw new Exception("手机号已存在");
        }
        return coachMapper.edit(coach);
    }

    @Override
    public int remove(Integer id) throws Exception {
        //1.查询数据库确认教练id是存在的
        Coach coach = coachMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(coach)) {
            //coach为空
            throw new Exception("教练不存在，无法删除");
        }
        //2.教练被删除之前，没有课程
        //***个人认为这里可以修改为在当前时间之后还有课程，那么不可删除
        //根据教练id，查询课程表，如果有数据，教练有课程，不能删除，如果没有课程，就可以删除
        List<Course> course = courseMapper.selectByCoachId(id);
        if (!course.isEmpty()) {
            throw new Exception("该教练还有课程无法删除");
        }
        return coachMapper.deleteById(id);
    }
}
